package com.inspur.edp.lcm.metadata.common;

import com.inspur.edp.metadata.rtcustomization.spi.MetadataRtSpi;
import io.iec.edp.caf.commons.utils.CollectionUtils;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 获取bean工厂
 *
 * @author liangff
 * @since 0.1.0
 * 2024/1/25
 */
public class ServiceFactory {
    private static ServiceFactory instance;

    public static ServiceFactory getInstance() {
        if (instance == null) {
            instance = new ServiceFactory();
        }
        return instance;
    }

    /**
     * 元数据删除扩展缓存，key为元数据类型，如ExternalApi
     */
    private Map<String, MetadataRtSpi> metadataRtServiceMap;

    /**
     * 根据元数据类型获取元数据删除扩展
     * @param metadataType 元数据类型
     * @return 元数据删除扩展
     */
    public MetadataRtSpi getMetadataRtService(String metadataType) {
        if (metadataRtServiceMap == null) {
            List<MetadataRtSpi> metadataRtSpiList = getService(MetadataRtSpi.class);
            metadataRtServiceMap = metadataRtSpiList.stream().collect(Collectors.toMap(MetadataRtSpi::getMetadataType, metadataRtSpi -> metadataRtSpi));
        }
        return metadataRtServiceMap.get(metadataType);
    }

    /**
     * 按照类型获取bean列表
     * @param tClass 类型
     * @return bean列表
     * @param <T> 类型
     */
    public <T> List<T> getService(Class<T> tClass) {
        Map<String, T> serviceMap = SpringBeanUtils.getApplicationContext().getBeansOfType(tClass);
        if (CollectionUtils.isEmpty(serviceMap)) {
            return new ArrayList<>();
        }
        return new ArrayList<>(serviceMap.values());
    }
}
